<template>
  <div>
    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px" label-position="left">
      <el-form-item :label="$t('common.upload')" prop="field" required>
        <el-upload ref="field" :limit="limit" :on-exceed="limitCheck" :headers="headers" :file-list="fileList"
          :on-progress="handleUploadProgress" :action="fieldAction" :on-success="handleUploadSuccess"
          :before-upload="fieldBeforeUpload">
          <el-button size="small" type="primary" icon="el-icon-upload">{{ $t('common.clickUpload') }}</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    // 上传数量
    limit: {
      type: Number,
      default: 100
    },
    // 最大上传文件大小
    limitFileSize: {
      type: Number,
      default: 1000
    },
  },
  data() {
    var token = this.$store.state.user.token
    return {
      formData: {
        field: null,
      },
      rules: {},
      fieldAction: process.env.VUE_APP_BASE_API + '/upload/uploadFile', // 上传地址
      fileList: [],
      headers: {
        Authorization: "Bearer " + token
      },
    };
  },
  watch: {},
  created() { },
  mounted() { },
  methods: {
    onOpen() { },
    onClose() {
      this.$refs["elForm"].resetFields();
    },
    // 超出文件总数时，触发
    limitCheck() {
      this.$message.warning(`最多选择${this.limit}个文件`)
    },
    handleUploadSuccess(res, file) {
      this.fileList = [
        {
          name: file.name,
          url: res,
        },
      ];
      this.$emit('input', this.fileList)
    },
    handleUploadProgress(e, file, fileList) {
      this.loading = true;
    },
    fieldBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2GB");
      }
      return isRightSize;
    },
  },
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
